package com.bp.hearthealth.pulse.lnapps.bp_utils

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.bp_extension.UIHelperBp
import com.hjq.toast.Toaster


/**
 * @author: isnoam
 * @package_name: LimitInputTextWatcher.kt
 * @description：
 */
class LimitInputTextWatcher(
    private val et: EditText?,
    private val regex: String,
    private val listener: AfterTextChangedListener
) : TextWatcher {

    override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
    override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
    override fun afterTextChanged(editable: Editable) {
        val str = editable.toString()
//        val inputStr = clearLimitStr(regex, str)
        val inputStr = clearLimitStr(str)
        et!!.removeTextChangedListener(this)
        editable.replace(0, editable.length, inputStr.trim { it <= ' ' })
        et.addTextChangedListener(this)
        listener.afterTextChanged(editable)
    }

    /**
     * 清除不符合条件的内容
     *
     * @param regex
     * @return
     */
    private fun clearLimitStr(regex: String, str: String): String {
        return str.replace(regex.toRegex(), "")
    }

    private fun clearLimitStr(str: String): String {
        return if (str.matches(Regex("^[1-9][0-9]*$"))) { //不能以0开头
            str
        } else {
            Toaster.show(UIHelperBp.getString(R.string._enter_data_within_the_range_str))
            ""
        }
    }
}

interface AfterTextChangedListener {
    fun afterTextChanged(editable: Editable)
}